import { defineStore } from 'pinia';
import { getToken, removeToken, setToken } from '../utils/token-utils';
import type { UserInfoState } from './interface';
import {ElMessage} from 'element-plus'
import {staticRoutes,asyncRoutes,anyRoutes} from '@/router/routes'
import {reqLogin,reqInfo,reqLogout} from '@/api/login/index'  
import  {cloneDeep} from 'lodash'
import  router from  '@/router/index'


// 过滤 路由方法
 const filterRoutes=(asyncRoute:any,routes:any)=>{
     console.log(asyncRoute);
     
    let   res=  asyncRoute.filter(item=>{
      if(item.children){
         item.children=filterRoutes(item.children,routes)
      }
        return   routes.includes(item.name)
      })

    return res
 }
 const addRoutes=(allRoutes:any)=>{
  allRoutes.forEach(item => {
       router.addRoute(item)
    
  });
      
 }
/**
 * 用户信息
 * @methods setUserInfos 设置用户信息
 */
export const useUserInfoStore = defineStore('userInfo', {

	state: (): UserInfoState => ({
    token: getToken() as string,
    name: '',
    avatar: '',
    menuRoutes: []
  }),

	actions: {
   async login (username: string, password: string) {
      let res=   await  reqLogin({username,password})
         setToken(res.token)
         this.token=getToken()
         
  
    },

   async getInfo () {
     let res=  await reqInfo()
       
       
     
     let filteredRoutes=filterRoutes(cloneDeep(asyncRoutes),res.routes)
     let allRoutes=staticRoutes.concat(filteredRoutes,anyRoutes)
     console.log(filteredRoutes);
     
      this.name = res.name
      this.avatar = res.avatar
      this.menuRoutes = allRoutes
    // 注册路由
      addRoutes(allRoutes)
    
    },

   async reset () {
       await reqLogout()
      // 删除local中保存的token
      removeToken()
      // 提交重置用户信息的mutation
      this.token = ''
      this.name = ''
      this.avatar = ''
    },
	},
});
